package studyguide.ch17;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.PushRegistry;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/**
 * To send sample messages, use "Utilities -> WMA Console" from Wireless Toolkit
 * @author Eduardo Ferreira
 */
public class SMSShowMidlet extends MIDlet {

	private final Command exitCommand;
	private final Display display;
	
	private final TextBox textBox;
	
	private class SampleCommandListener implements CommandListener {
		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
	}
	
	public SMSShowMidlet() throws IOException {
		textBox = new TextBox("Notification", "", 500, TextField.UNEDITABLE);
		exitCommand = new Command("Exit", Command.EXIT, 1);
		
		textBox.addCommand(exitCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		textBox.setCommandListener(listener);
		display = Display.getDisplay(this);
	}
	
	protected void destroyApp(boolean unconditional) {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		
		// List only connections where data is available
		String connections[] = PushRegistry.listConnections(true);
		
		if (connections.length == 0) {
			textBox.setString("You have no messages.");
		} else {
			textBox.setString("Please wait...");
			// Only one registration is expected
			final String connectionURL = connections[0];
			Thread thread = new Thread(new Runnable() {
				public void run() {
					MessageConnection connection = null;
					try {
						connection = (MessageConnection) Connector.open(connectionURL);
						TextMessage message = (TextMessage) connection.receive();
						textBox.setString("You have received the following notification:" + message.getPayloadText());
					} catch (Exception e) {
						textBox.setString("Error receiving message:" + e);
					} finally {
						if (connection != null) {
							try {
								// This is wrong: This application is unable to receive messages while
								// it is running!
								connection.close();
							} catch (IOException e) {
								textBox.setString("Error closing resourcesb:" + e);
							}
						}
					}
				}
			});
			thread.start();
		}
		
		display.setCurrent(textBox);	
	}

}
